package cn.ryh.gat1400.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Author: aiLin
 * @Date: 2020/5/16 15:11
 * @desc: 在多线程处理问题时，无法通过@Autowired注入bean，报空指针异常，在线程中为了线程安全，是防注入的，如果要用到这个类，只能从bean工厂里拿个实例
 */
//手动获取Spring中的bean  注意这个类要一定交给spring来管理
@Component
public class BeanContext implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BeanContext.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T)applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clz) throws BeansException {
        return (T)applicationContext.getBean(clz);
    }
}
